<template>
  <div class="flex flex-col w-full h-full">
    <!-- 表格容器 -->
    <div ref="tableContainer" class="flex-1 relative overflow-hidden bg-white"></div>
    
    <!-- 工具栏（可选） -->
    <div v-if="showToolbar" class="flex gap-2 p-2 border-b border-gray-200 bg-gray-50">
      <slot name="toolbar">
        <!-- 默认工具栏内容 -->
        <button 
          @click="undo" 
          :disabled="!canUndo"
          class="px-3 py-1 text-sm border border-gray-300 bg-white rounded hover:border-blue-500 hover:text-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          撤销
        </button>
        <button 
          @click="redo" 
          :disabled="!canRedo"
          class="px-3 py-1 text-sm border border-gray-300 bg-white rounded hover:border-blue-500 hover:text-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          重做
        </button>
        <button 
          @click="exportData"
          class="px-3 py-1 text-sm border border-gray-300 bg-white rounded hover:border-blue-500 hover:text-blue-500 transition-colors"
        >
          导出
        </button>
        <button 
          @click="importFile"
          class="px-3 py-1 text-sm border border-gray-300 bg-white rounded hover:border-blue-500 hover:text-blue-500 transition-colors"
        >
          导入
        </button>
      </slot>
    </div>
    
    <!-- 状态栏（可选） -->
    <div v-if="showStatusBar" class="flex gap-4 px-3 py-1 border-t border-gray-200 bg-gray-50 text-xs text-gray-600">
      <slot name="status">
        <span>行数: {{ statistics.totalRows }}</span>
        <span>列数: {{ statistics.totalColumns }}</span>
        <span v-if="statistics.modifiedCells > 0" class="text-amber-600">
          已修改: {{ statistics.modifiedCells }} 个单元格
        </span>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { CanvasTable } from './core/CanvasTable'
import { EventType } from './types'
import type { 
  Column, 
  RowData, 
  TableOptions,
  CellClickEvent,
  CellChangeEvent,
  CellPosition
} from './types'

// Props
const props = withDefaults(defineProps<{
  columns: Column[]
  data: RowData[]
  options?: TableOptions
  showToolbar?: boolean
  showStatusBar?: boolean
  height?: number | string
  width?: number | string
}>(), {
  showToolbar: false,
  showStatusBar: false
})

// Emits
const emit = defineEmits<{
  'cell-click': [event: any]
  'cell-double-click': [event: any]
  'cell-change': [event: any]
  'selection-change': [event: any]
  'row-click': [event: any]
  'column-click': [event: any]
  'data-change': [data: any[]]
  'column-resize': [event: { column: number; width: number }]
  'row-resize': [event: { row: number; height: number }]
  'context-menu': [event: any]
  'copy': [event: any]
  'paste': [event: any]
  'cut': [event: any]
  'save': [changes: any]
  'batch-edit': [event: any]
  'batch-delete': [event: any]
  'edit-start': [event: any]
  'edit-end': [event: any]
  'sort': [event: any]
}>()

// Refs
const tableContainer = ref<HTMLElement>()

// State
const table = ref<CanvasTable | null>(null)
const canUndo = ref(false)
const canRedo = ref(false)
const statistics = ref({
  totalRows: 0,
  totalColumns: 0,
  modifiedCells: 0,
  insertedRows: 0,
  deletedRows: 0
})

// 计算容器样式
const containerStyle = computed(() => ({
  height: typeof props.height === 'number' ? `${props.height}px` : props.height,
  width: typeof props.width === 'number' ? `${props.width}px` : props.width
}))

// 初始化表格
onMounted(() => {
  console.log('CanvasTable.vue - onMounted')
  if (!tableContainer.value) return
  
  // 创建表格实例
  table.value = new CanvasTable(
    tableContainer.value,
    props.columns,
    props.options
  )
  console.log('CanvasTable.vue - 创建了新的 CanvasTable 实例')
  
  // 设置初始数据 - 无论有没有数据都调用 setData
  const initialData = Array.isArray(props.data) ? props.data : []
  table.value.setData(initialData)
  
  // 监听事件
  setupEventListeners()
  
  // 更新状态
  updateStatistics()
})

// 清理
onUnmounted(() => {
  if (table.value) {
    table.value.destroy()
    table.value = null
  }
})

// 监听数据变化
watch(() => props.data, (newData) => {
  if (table.value) {
    // 如果有未保存的更改，不要覆盖数据
    // 这样可以避免新增的行在滚动时消失
    const changes = table.value.getChanges()
    if (changes && (changes.modified.length > 0 || changes.inserted.length > 0 || changes.deleted.length > 0)) {
      console.warn('有未保存的更改，跳过数据更新以保留本地修改')
      return
    }
    
    // 将 null 或 undefined 转换为空数组，确保始终设置有效值
    const dataToSet = Array.isArray(newData) ? newData : []
    table.value.setData(dataToSet)
    updateStatistics()
  }
})

// 监听列配置变化
watch(() => props.columns, (newColumns) => {
  if (table.value && !table.value.isDestroyed()) {
    // 重新创建表格前先保存当前数据
    const currentData = table.value.getData()
    
    // 销毁旧表格
    table.value.destroy()
    table.value = null
    
    // 创建新表格
    if (tableContainer.value) {
      table.value = new CanvasTable(
        tableContainer.value,
        newColumns,
        props.options
      )
      table.value.setData(currentData)
      setupEventListeners()
      updateStatistics()
    }
  }
})

// 监听选项变化
watch(() => props.options, (newOptions) => {
  if (table.value && newOptions) {
    // 更新主题
    if (newOptions.theme) {
      table.value.setTheme(newOptions.theme)
    }
    // 更新其他选项
    if (newOptions.showRowNumber !== undefined) {
      table.value.toggleRowNumbers(newOptions.showRowNumber)
    }
    if (newOptions.showGridLines !== undefined) {
      table.value.toggleGridLines(newOptions.showGridLines)
    }
  }
})

// 设置事件监听
function setupEventListeners() {
  if (!table.value) return
  
  // 单元格点击
  table.value.on(EventType.CellClick, (event: CellClickEvent) => {
    emit('cell-click', event)
  })
  
  // 单元格修改
  table.value.on(EventType.CellChange, (event: CellChangeEvent) => {
    emit('cell-change', event)
    emit('data-change', table.value!.getData())
    updateStatistics()
    updateUndoRedoState()
  })
  
  // 选择变化
  table.value.on(EventType.SelectionChange, () => {
    const cells = table.value!.getSelectedCells()
    emit('selection-change', cells)
  })
  
  // 编辑开始
  table.value.on(EventType.EditStart, (event: any) => {
    emit('edit-start', event)
  })
  
  // 编辑结束
  table.value.on(EventType.EditEnd, (event: any) => {
    emit('edit-end', event)
  })
  
  // 排序事件
  table.value.on(EventType.Sort, (event: any) => {
    emit('sort', event)
  })
}

// 更新统计信息
function updateStatistics() {
  if (!table.value) return
  statistics.value = table.value.getStatistics()
}

// 更新撤销重做状态
function updateUndoRedoState() {
  if (!table.value) return
  canUndo.value = table.value.canUndo()
  canRedo.value = table.value.canRedo()
}

// 撤销
function undo() {
  if (!table.value) return
  table.value.undo()
  updateStatistics()
  updateUndoRedoState()
  emit('data-change', table.value.getData())
}

// 重做
function redo() {
  if (!table.value) return
  table.value.redo()
  updateStatistics()
  updateUndoRedoState()
  emit('data-change', table.value.getData())
}

// 导出数据
function exportData() {
  if (!table.value) return
  
  const format = 'csv' // 可以通过对话框让用户选择格式
  const data = table.value.exportData({
    format,
    includeHeaders: true,
    selectedOnly: false
  })
  
  // 下载文件
  const blob = new Blob([data], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `table-export-${Date.now()}.${format}`
  a.click()
  URL.revokeObjectURL(url)
}

// 导入文件
function importFile() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.csv,.tsv,.json'
  
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file || !table.value) return
    
    const text = await file.text()
    const format = file.name.endsWith('.json') ? 'json' : 
                   file.name.endsWith('.tsv') ? 'tsv' : 'csv'
    
    try {
      table.value.importData(text, {
        format,
        hasHeaders: true,
        append: false
      })
      
      emit('data-change', table.value.getData())
      updateStatistics()
    } catch (error) {
      console.error('导入失败:', error)
      // TODO: 显示错误提示
    }
  }
  
  input.click()
}

// 暴露方法
defineExpose({
  // 获取表格实例
  getTable: () => table.value,
  
  // 获取修改的数据
  getChanges: () => table.value?.getChanges(),
  
  // 提交修改
  commit: () => {
    table.value?.commit()
    updateStatistics()
    updateUndoRedoState()
  },
  
  // 回滚修改
  rollback: () => {
    table.value?.rollback()
    emit('data-change', table.value!.getData())
    updateStatistics()
    updateUndoRedoState()
  },
  
  // 撤销/重做
  undo,
  redo,
  
  // 数据操作
  insertRow: (index: number, row?: RowData) => {
    table.value?.insertRow(index, row)
    emit('data-change', table.value!.getData())
    updateStatistics()
  },
  
  deleteRow: (index: number) => {
    table.value?.deleteRow(index)
    emit('data-change', table.value!.getData())
    updateStatistics()
  },
  
  // 批量更新
  batchUpdate: (updates: Array<{ row: number; col: number; value: any }>) => {
    table.value?.batchUpdate(updates)
    emit('data-change', table.value!.getData())
    updateStatistics()
  },
  
  // 查找
  findCell: (predicate: (value: any, row: number, col: number) => boolean) => {
    return table.value?.findCell(predicate)
  },
  
  findAllCells: (predicate: (value: any, row: number, col: number) => boolean) => {
    return table.value?.findAllCells(predicate)
  },
  
  // 导入导出
  exportData: () => {
    return table.value?.exportData()
  },
  
  importData: (data: string, options?: any) => {
    table.value?.importData(data, options)
    emit('data-change', table.value!.getData())
    updateStatistics()
  },
  
  // 刷新
  refresh: () => table.value?.refresh(),
  
  // 获取统计信息
  getStatistics: () => statistics.value
})
</script>

<style scoped>
/* 导入右键菜单样式 */
@import './styles/context-menu.css';

/* 编辑器样式 - 保留因为是动态创建的 */
:global(.canvas-table-editor) {
  @apply absolute z-[1000];
}
</style> 